/**
 * 
 */
package soa.security.web;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import soa.security.domain.Account;
import soa.security.mgr.service.AccountMgrService;

/**
 * @author Cre.Gu
 *
 */
public class LdapRealm extends AuthorizingRealm {

	@Resource
	protected AccountMgrService accountMgrService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		return new SimpleAuthorizationInfo();
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		LdapUsernamePasswordCaptchaToken token = (LdapUsernamePasswordCaptchaToken) authcToken;
		String username = token.getUsername();
		String organizationDn = token.getOrganizationDn();
		String password = new String(token.getPassword());

		try {
			Account account = accountMgrService.systemLogin(username,
					organizationDn, password);
			if (account == null)
				return null;

			if (account.isDisable())
				throw new AuthenticationException("登录失败");

			return new SimpleAuthenticationInfo(account.getDn().toString(),
					account.getPassword(), account.getBid());
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new AuthenticationException("登录失败");
		}
	}
}
